import { Ability, AbilityClass } from '@casl/ability';

export type Actions = 'manage' | 'create' | 'read' | 'update' | 'delete';
export type Subjects = 'Dictionary' | 'all';

export enum Action {
  manage = 'manage',
  create = 'create',
  read = 'read',
  update = 'update',
  delete = 'delete',
}

export type Abilities = Ability<[Actions, Subjects]>;
export const AppAbility = Ability as AbilityClass<Abilities>;

export function defineRulesFor(permissions: any[], superAdmin: boolean) {
  if (superAdmin) {
    return [
      {
        action: Action.manage,
        subject: 'all',
      },
    ];
  }

  return permissions.map((item) => {
    console.log('item.conditions', JSON.parse(item.conditions))
    return {
      action: item.action,
      subject: item.subject,
      conditions: item.conditions ? JSON.parse(item.conditions) : undefined,
    };
  });
}
